package com.example.oschina.activity

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.oschina.R
import com.example.oschina.databinding.ActivityWebviewBinding
import com.example.oschina.utils.Constants
import com.example.oschina.utils.Utils

class MyWebView : AppCompatActivity() {
  private lateinit var progressBar: ProgressBar

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val webviewBinding =
      DataBindingUtil.setContentView<ActivityWebviewBinding>(this, R.layout.activity_webview)
    val mWebView = webviewBinding.webview

    mWebView.settings.setSupportZoom(false)
    mWebView.isHorizontalScrollBarEnabled = false
    mWebView.isVerticalScrollBarEnabled = false
    mWebView.settings.javaScriptEnabled = true
    mWebView.settings.domStorageEnabled = true

    mWebView.settings.cacheMode = WebSettings.LOAD_DEFAULT

    mWebView.webViewClient = object : WebViewClient() {
      override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        view.loadUrl(url)
        val uri = Uri.parse(url)
        val code = uri.getQueryParameter("code")
        if (!TextUtils.isEmpty(code)) {
          setResultAndFinishActivity(code)
        }
        return true
      }
    }

    progressBar = findViewById<View>(R.id.load_progress_bar) as ProgressBar
    progressBar.visibility = View.VISIBLE
    mWebView.webChromeClient = object : WebChromeClient() {
      override fun onProgressChanged(view: WebView, progress: Int) {
        // Activity和Webview根据加载程度决定进度条的进度大小
        // 当加载到100%的时候 进度条自动消失
        progressBar.progress = progress
        if (progressBar.max == progress) {
          progressBar.visibility = View.GONE
        }
      }
    }
    val url = intent.getStringExtra(Constants.WEB_URL)
    if (!TextUtils.isEmpty(url)) {
      mWebView.loadUrl(url)
    }
  }

  fun setResultAndFinishActivity(code: String) {
    progressBar.postDelayed({
      val i = Intent()
      i.putExtra(Utils.REDIRECT_CODE, code)
      setResult(Activity.RESULT_OK, i)
      finish()
    }, 1000)
  }

  companion object {
    private val TAG = MyWebView::class.java.simpleName
  }

}